package com.abocode.smarten.rpc.server.netty;

import com.abocode.smarten.rpc.server.ConfigPushService;
import com.abocode.smarten.rpc.server.PushService;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Description:
 * @author: guanxianfei
 * @date: 2019/7/23
 */
@Slf4j
@ChannelHandler.Sharable
public class ServerHandler extends SimpleChannelInboundHandler<String> implements PushService {
    public static Map<ConfigProperties, List<ClientConfig>> clients=new ConcurrentHashMap<ConfigProperties, List<ClientConfig>>();
    private ConcurrentHashMap<String, ChannelHandlerContext> channels =new ConcurrentHashMap<String, ChannelHandlerContext>();

    @Autowired
    private ConfigPushService configPushService;

    protected void channelRead0(ChannelHandlerContext ctx, String request)  {
        if (request != null && request.startsWith("config=")) {
            request = request.substring("config=".length());
            Map<String, Object> params = JsonUtils.parse2Map(request);
            String projectCode = params.get("projectCode").toString();
            String profile = params.get("profile").toString();
            String moduleCodes = params.get("moduleCodes").toString();
            String[] moduleCode= moduleCodes.split(",");
            ConfigProperties key = new ConfigProperties(projectCode,profile,moduleCode);

            List<ClientConfig> addrs = clients.get(key);
            if(addrs == null) {
                addrs = new ArrayList<ClientConfig>();
            }

            String clientAddress= ctx.channel().remoteAddress().toString();
            ClientConfig clientConfig = new ClientConfig(clientAddress, new Date());
            addrs.add(clientConfig);
            clients.put(key, addrs);
            channels.put(clientAddress, ctx);
            configPushService.pushConfig(projectCode,profile,moduleCode);
        }
    }

    public void channelActive(ChannelHandlerContext ctx)  {
        log.debug(ctx.channel().remoteAddress() + " 连接到服务器。");
    }

    private void sendMessage(ChannelHandlerContext ctx, String content) {
        byte[] bytes =content.getBytes();
        ByteBuf message = Unpooled.buffer(4 + bytes.length);
        message.writeInt(bytes.length);
        message.writeBytes(bytes);
        ctx.writeAndFlush(message);
    }

    public void pushAll(String content) {
        for(ConfigProperties key : clients.keySet()) {
                List<ClientConfig> clientConfigs = clients.get(key);
                if(clientConfigs != null) {
                    for(ClientConfig client : clientConfigs) {
                        ChannelHandlerContext ctx = channels.get(client.getAddress());
                        if(ctx != null) {
                            sendMessage(ctx,content);
                        }
                }
            }
        }
    }

    public void pushAll(String profile, String content) {
         throw  new  RuntimeException("this method does't impl");
    }
}
